<template>
    <div>
      <div class="search">
          <input v-model="keyword" class="search-input" type="text" placeholder="请输入城市名和拼音">
      </div>
      <div class="search-result" ref="search" v-show="keyword">
        <ul>
          <li class="result-list border-bottom" @click="handleCityClick(item.name)" v-for="item of list" :key="item.id">{{item.name}}</li>
          <li class="result-list border-bottom" v-show="hasNoData">没有找到匹配的城市</li>
        </ul>
      </div>
    </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: 'HeaderSearch',
  props: {
    citylist: Object
  },
  data() {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleCityClick(cityname) {
      this.changeCity(cityname)
      this.$router.push({path: '/'})
    },
    ...mapMutations(['changeCity'])
  },
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (const i in this.citylist) {
          this.citylist[i].forEach((value) => {
            if (value.name.indexOf(this.keyword) > -1 || value.spell.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted() {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.search
  height 0.72rem
  background $bgColor
  padding 0 .1rem
  .search-input
    box-sizing border-box
    height .62rem
    line-height .62rem
    width 100%
    color #666
    padding 0 .1rem
    border-radius .06rem
    text-align center
.search-result
  overflow hidden
  position absolute
  top 1.4rem
  left 0
  right 0
  bottom 0
  background #ccc
  z-index 1
  .result-list
    height .62rem
    line-height .62rem
    padding-left .2rem
    color #666
    background #fff
</style>
